
const fs = require('fs');
const exec = require('./exec')
const utils = require('./utils')
const config = require('./env');
let SESSIONIDD2;
const increase = 1000000;

async function main(price,arg = [],page = 0) {
	const res = await utils.request('https://api.stepn.com/run/orderlist',{
		order:1002,
		type:603,
		quality:1,
		level:6031,
		chain:103,
		refresh:arg.length === 0,
	},'get',SESSIONIDD2);
	if(res.code === -2) {
		return relogin();
	}
	if(res.code === 0) {
		await utils.sleep(3000);
		page += 1;
		console.log(`第${page}页`);
		const data = res.data || [];
		let hasShoe = false;
		data.sort((a,b) =>a.sellPrice-b.sellPrice)
		for(let i =0;i<data.length;i++) {
			const item = data[i];
			if(item.sellPrice <= price) {
				const attrs = await detail(item['id']);
				await utils.sleep(3000);
				if(((attrs[0]+attrs[3])/10 >=13 ) && (attrs[3]+attrs[7]+attrs[11])/10 <= 9) {
					hasShoe = true;
					//发送实时价格
					await utils.postMessage(config.hook,handleFormatData({...item,attrs},price))
				}
			}
		}
		if(!hasShoe) {
			await utils.postMessage(config.hook,reulstNotice('暂无满足条件的鞋子'));
		}else{
			await utils.postMessage(config.hook,reulstNotice('当前列表已更新完成'));
		}		
		fs.writeFileSync('status','true','utf8');
		// exit(0)
	}
}
function reulstNotice(value) {
	return {
		msg_type:"post",
		content:{
			post:{
				"zh_cn":{
					title:"",
					content:[
						[
							{
								tag:"text",
								"un_escape":true,
								"text":`${value}\n`
							}
						],					
						[
							{
								tag:'a',
								href:`${config.request}/refresh`,
								text:'获取最新数据\n',
							},
						],
					]
				}
			}
		}
	}
}
function handleFormatData(item,price) {
	const content = {
		msg_type:"post",
		content:{
			post:{
				"zh_cn":{
					title:"",
					content:[
						[
							{
								tag:'text',
								un_escape:true,
								text:`编号：${item.otd}\n`
							},
							{
								tag:'text',
								un_escape:true,
								text:`售价：${item.sellPrice/increase} SOL\n`
							},
							{
								tag:"text",
								"un_escape":true,
								"text":`当前地板价：${(price-increase)/increase}\n`
							},
							{
								tag:'text',
								un_escape:true,
								text:`Base Total:${(item.attrs[0]+item.attrs[3])/10}\n`
							},
							{
								tag:'text',
								un_escape:true,
								text:`等级：${item.level}\n`
							},
							{
								tag:'text',
								un_escape:true,
								text:`Base Efficiency:${item.attrs[0]/10}\n`
							},
							{
								tag:'text',
								un_escape:true,
								text:`Base Resilience:${item.attrs[3]/10}\n`
							},
							
							{
								tag:'text',
								un_escape:true,
								text:`Total Resilience:${(item.attrs[3]+item.attrs[7]+item.attrs[11])/10}\n`
							},
							{
								tag:'a',
								href:`${config.request}/buy?orderId=${item.id}&price=${item.sellPrice}`,
								text:'一键购买\n',
							},
							{
								tag:'text',
								un_escape:true,
								text:`---------------`
							},
						],
					]
				}
			}
		}
	};
	return content;
}
async function lowestPrice() {
	const res = await utils.request('https://api.stepn.com/run/orderlist',{
		order:2001,
		type:603,
		quality:1,
		level:6031,
		chain:103,
		refresh:true,
	},'get',SESSIONIDD2);
	if(res.code === -2) {
		return relogin();
	}
	if(res.code === 0) {
		const data = res.data ? res.data : [];
		const lowestPrice = data[0] ? data[0].sellPrice : 0;
		console.log(`当前地板价: ${lowestPrice/increase}`);
		main(lowestPrice+increase,[]);
	}
}
async function detail(id) {
	console.log('执行中',id);
	const res = await utils.request(`https://api.stepn.com/run/orderdata?orderId=${id}`,{},'get',SESSIONIDD2);
	if(res.code === 0) {
		return res.data.attrs;
	}else {
		return [0,0,0,0,0,0,0,0,0,0,0,0];
	}
}

function relogin() {
	let i = 0;
	const timer = setInterval(() =>{
		const res = fs.readFileSync('session','utf8')
		if(SESSIONIDD2 !== res) {
			clearInterval(timer);
			SESSIONIDD2 = res;
			lowestPrice();
		}
		if(i>=10) {
			console.log('获取新的SESSION超时');
			clearInterval(timer);
			lowestPrice();
		}
		i++
	},5000);
	exec.launchApp();
}

module.exports = async function init() {
	console.log('启动')
	await utils.sleep();
	SESSIONIDD2 = fs.readFileSync('session','utf8');
	console.log('当前SEESION：：：',SESSIONIDD2);
	lowestPrice();
}
